

















package record;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.qingning.qn.R;
import com.tekartik.sqflite.Constant;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

import base.BaseActivity;
import utils.MainConstants;


public class PlayerVideoActivity extends BaseActivity implements SurfaceHolder.Callback, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
        MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, View.OnClickListener {

    SurfaceView video;
    Button btSub;
    MediaPlayer player;
    // 传递过来的视频简历path
    String videoPath;
    // 视频大小
    double videoSize;
    // 视频时长
    int videoTime;


    SurfaceHolder sHolder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player_video);
        initView();
        addListener();
    }


    public void initView() {
        video = (SurfaceView) findViewById(R.id.video);
        btSub = (Button) findViewById(R.id.btSub);

        videoPath = getIntent().getStringExtra("videoPath");

        btSub.setVisibility(View.VISIBLE);
        videoSize = contBufferForMB(new File(videoPath));
        Log.e("TAG", "videoSize = " + videoSize);
        Log.e("TAG", "视频地址 = " + videoPath);

        // 设置surfaceHolder
        sHolder = video.getHolder();
        // 设置Holder类型,该类型表示surfaceView自己不管理缓存区,虽然提示过时，但最好还是要设置
        sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // 设置surface回调
        sHolder.addCallback(this);
    }


    public void addListener() {
        btSub.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // 上传视频,判断视频时长和大小
        if (videoSize > 10) {
            Toast.makeText(this, "视频不能大于10M，提交失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if (videoTime >= 11000) {
            Toast.makeText(this, "视频过长，提交失败", Toast.LENGTH_SHORT).show();
            return;
        }
        /*if (videoTime < 5000) {
            Toast.makeText(this, "视频过短，提交失败", Toast.LENGTH_SHORT).show();
            return;
        }*/

        setResult(RESULT_OK);
        finish();
    }


    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        // surfaceView被创建
        // 设置播放资源
        playVideo();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        // surfaceView销毁,同时销毁mediaPlayer
        if (null != player) {
            // 提前标志为false,防止在视频停止时，线程仍在运行。
            // seekBarAutoFlag = false;
            // 如果正在播放，则停止。
            if (player.isPlaying()) {
                player.stop();
            }
            // 释放mediaPlayer
            player.release();
            player = null;
        }
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        int width = mediaPlayer.getVideoWidth();
        int height = mediaPlayer.getVideoHeight();
        Log.e("TAG", "width = " + width + "\nheight = " + height);

        videoTime = player.getDuration();
        Log.e("TAG", "time = " + videoTime);

        resetSize();


        // 判断是否有保存的播放位置,防止屏幕旋转时，界面被重新构建，播放位置丢失。
        if (MainConstants.playPosition >= 0) {
            mediaPlayer.seekTo(MainConstants.playPosition);
            MainConstants.playPosition = -1;
            // surfaceHolder.unlockCanvasAndPost(Constants.getCanvas());
        }

        // 播放视频
        mediaPlayer.start();
        // 设置显示到屏幕
        mediaPlayer.setDisplay(sHolder);
//        // 开启线程 刷新进度条
//        new Thread(runnable).start();
        // 设置surfaceView保持在屏幕上
        mediaPlayer.setScreenOnWhilePlaying(true);
        sHolder.setKeepScreenOn(true);

    }

    private void resetSize() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int screenWidth = outMetrics.widthPixels;
        int screenHeight = outMetrics.heightPixels;


        float areaWH = screenWidth * 1.0f / screenHeight;
        int height;

        height = (int) (screenWidth * 1.0f / screenWidth / screenHeight);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        video.setLayoutParams(layoutParams);

        int mediaWidth = player.getVideoWidth();
        int mediaHeight = player.getVideoHeight();


        float mediaWH = mediaWidth * 1.0f / mediaHeight;

        RelativeLayout.LayoutParams layoutParamsSV = null;


        if (areaWH > mediaWH) {
            //直接放会矮胖
            int svWidth = (int) (height * mediaWH);
            layoutParamsSV = new RelativeLayout.LayoutParams(svWidth, height);
            Log.e("TAG", "计算过后的宽 = " + svWidth);
            Log.e("TAG", "计算过后的高 = " + height);
            layoutParamsSV.addRule(RelativeLayout.CENTER_IN_PARENT);
            video.setLayoutParams(layoutParamsSV);
        }
        if (areaWH < mediaWH) {
            //直接放会瘦高。
            int svHeight = (int) (screenWidth / mediaWH);
            layoutParamsSV = new RelativeLayout.LayoutParams(screenWidth, svHeight);
            Log.e("TAG", "计算过后的宽 = " + screenWidth);
            Log.e("TAG", "计算过后的高 = " + svHeight);
            layoutParamsSV.addRule(RelativeLayout.CENTER_IN_PARENT);
            video.setLayoutParams(layoutParamsSV);
        }

        if (areaWH == mediaWH) {
            layoutParamsSV = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParamsSV.addRule(RelativeLayout.CENTER_IN_PARENT);
            video.setLayoutParams(layoutParamsSV);
        }

    }


    /**
     * 播放视频
     */
    public void playVideo() {
        // 初始化MediaPlayer
        player = new MediaPlayer();
        // 重置mediaPaly,建议在初始滑mediaplay立即调用。
        player.reset();
        // 设置声音效果
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        // 设置播放完成监听
        player.setOnCompletionListener(this);
        // 设置媒体加载完成以后回调函数。
        player.setOnPreparedListener(this);
        // 错误监听回调函数
        player.setOnErrorListener(this);
        // 设置缓存变化监听
        player.setOnBufferingUpdateListener(this);
        player.setLooping(true);
        try {
            // mediaPlayer.reset();
            player.setDataSource(videoPath);
            // mediaPlayer.setDataSource(this, uri);
            // mediaPlayer.setDataSource(SurfaceViewTestActivity.this, uri);
            // 设置异步加载视频，包括两种方式 prepare()同步，prepareAsync()异步
            player.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "加载视频错误", Toast.LENGTH_LONG).show();
        }
    }


    /**
     * 播放完毕监听
     */
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {

    }

    /**
     * 错误监听
     *
     * @return
     */
    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
        return false;
    }

    /**
     * 视频缓存大小监听,当视频播放以后 在started状态会调用
     */
    @Override
    public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
        // percent 表示缓存加载进度，0为没开始，100表示加载完成，在加载完成以后也会一直调用该方法
//        Log.e("text", "onBufferingUpdate-->" + percent);
        // 可以根据大小的变化来
    }

    @Override
    public void onPause() {
        super.onPause();
        if (null != player && player.isPlaying()) {
            MainConstants.playPosition = player.getCurrentPosition();
            player.pause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            if (null != player && MainConstants.playPosition > 0) {
                player.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 播放下标重置
        MainConstants.playPosition = -1;
        if (null != this.player) {
            // 提前标志为false,防止在视频停止时，线程仍在运行。
            // seekBarAutoFlag = false;
            // 如果正在播放，则停止。
            if (player.isPlaying()) {
                player.stop();
            }
            // 释放mediaPlayer
            this.player.release();
            this.player = null;
        }
    }


    /**
     * @param file 传入文件夹路径的对象
     * @return 返回文件夹大小
     */
    private double contBufferForMB(File file) {
        if (file != null) {
            if (file.exists()) {
                // 如果是目录则递归计算其内容的总大小
                if (file.isDirectory()) {
                    File[] children = file.listFiles();
                    double size = 0;
                    for (File f : children) {
                        size += contBuffer(f);
                    }
                    return (int) size;
                } else {
                    // 如果是文件则直接返回其大小,以“KB”为单位
                    double size = (double) file.length();

                    double kiloByte = size / 1024;
                    if (kiloByte < 1) {
                        return 1;
                    }

                    double megaByte = kiloByte / 1024;
                    if (megaByte < 1) {
                        return 1;
                    }
                    BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
                    return result2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                }
            }
        }
        return 0;
    }

    /**
     * @param file 传入文件夹路径的对象
     * @return 返回文件夹大小
     */
    private double contBuffer(File file) {
        if (file != null) {
            if (file.exists()) {
                // 如果是目录则递归计算其内容的总大小
                if (file.isDirectory()) {
                    File[] children = file.listFiles();
                    double size = 0;
                    for (File f : children) {
                        size += contBuffer(f);
                    }
                    return (int) size;
                } else {// 如果是文件则直接返回其大小,以“byte”为单位
                    double size = (double) file.length();
                    return (double) size;
                }
            }
        }
        return 0;
    }

}

















